Django 传递JSON至JS处理

您所在的位置:网站首页 django json传递列表 Django 传递JSON至JS处理

Django 传递JSON至JS处理

2024-07-12 01:00| 来源: 网络整理| 查看: 265

学习来源:Django传值给前端

非ajax,这里是将json与网页一次性全部发给浏览器端,不是异步传输。

模版html:

学习 //列表 var List = {{ List|safe }}; //下面的代码把List的每一部分放到头部和尾部 $('#list').prepend(List[0]); $('#list').append(List[1]); console.log('--- 遍历 List 方法 1 ---') for(i in List){ console.log(i);// i为索引 } console.log('--- 遍历 List 方法 2 ---') for (var i = List.length - 1; i >= 0; i--) { // 鼠标右键,审核元素,选择 console可以看到输入的值 console.log(List[i]); }; console.log('--- 同时遍历索引和内容,使用 jQuery.each() 方法 ---') $.each(List, function(index, item){ console.log(index); console.log(item); }); // 字典 var Dict = {{ Dict|safe }}; console.log("--- 两种字典的取值方式 ---") console.log(Dict['site']); console.log(Dict.author); console.log("--- 遍历字典 ---"); for(i in Dict) { console.log(i + Dict[i]);//注意,此处 i 为键值 }

urls:

from django.urls import path from . import views app_name = 'tttt' urlpatterns = [ path('', views.home, name='index'), ]

视图层:

from django.shortcuts import render import json # Create your views here. def home(request): List = ['自强学堂', '渲染Json到模板'] Dict = {'site': '自强学堂', 'author': '涂伟忠'} return render(request, 'tttt/home.html', { 'List': json.dumps(List), 'Dict': json.dumps(Dict) })

f12查看终端即可查看结果。

使用echarts等要js处理的东西时,Django就这样操作将数据发给前端处理即可。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3